# -*- coding: utf-8 -*-

import json

from apps.common.base import BaseHandler, requires_auth
from apps.utils import Utils


class DeviceListHandler(BaseHandler):
    """
    设备列表 /device/list
    """
    @requires_auth
    async def get(self, cuser, *args, **kwargs):
        page = self.get_argument('page', default=1)
        limit = self.get_argument('limit', default=15)
        offline = self.get_argument('offline', default=0)
        query = self.get_argument('query', default='')
        
        try:
            devices = await self.device_model.get_devices(
                cuser['id'], int(page), int(limit), int(offline), query)
        except ValueError:
            return self.render_json(-1, '数据类型错误')

        lists = []
        if devices:
            for i in devices:
                monitor_cache = self.cache_action.rptsys().get(i['sn'])
                if monitor_cache:
                    monitor_cache = json.loads(monitor_cache)
                else:
                    monitor_cache = {
                        'area': '未知',
                        'cpuidle': '未知',
                        'diskusage': '未知',
                        'freemem': '未知',
                        'ioutil': '未知',
                        'pingtime': '未知'
                    }
                if i['online_time'] is not None:
                    online_time = Utils.format_time(i['online_time'])
                else:
                    online_time = '未知'
                data = {
                    'offline': i['offline'],
                    'id': i['id'],
                    'uuid': i['uuid'],
                    'sn': i['sn'],
                    'status': i['status'],
                    'user_id': i['user_id'],
                    'name': i['name'],
                    'online_time': online_time,
                    'add_time': Utils.format_time(i['add_time']),
                    'monitor': monitor_cache
                }
                lists.append(data)
        return self.render_json(0, 'success', {
            'device': lists,
        })


class DeviceAddHandler(BaseHandler):
    """
    设备添加 /device/add
    """
    @requires_auth
    async def post(self, cuser, *args, **kwargs):
        sn = self.get_argument('sn', default='')
        name = self.get_argument('name', default='')

        if Utils.is_null(sn):
            return self.render_json(-1, '设备SN不能为空！')
        if Utils.is_null(name):
            return self.render_json(-1, '设备名称不能为空！')
        if await self.device_model.get_device_by_sn(sn):
            return self.render_json(-1, '系统已经存在这个SN设备，不可添加')

        device = await self.device_model.add_new_device(Utils.get_uuid(),
                                                          status=2,
                                                          sn=sn,
                                                          name=name,
                                                          offline=2,
                                                          user_id=cuser['id'])
        if device:
            return self.render_json(0, '设备添加成功')
        else:
            return self.render_json(-1, '设备添加失败')


class DeviceInfoHandler(BaseHandler):
    """
    设备详情 /device/info/<uuid>
    """
    @requires_auth
    async def get(self, cuser, *args, **kwargs):
        uuid = self.get_argument('uuid', default='')
        if not uuid:
            return self.render_json(-1, '设备uuid为空')
        device = await self.device_model.get_device_by_uuid_and_userid(
            uuid, cuser['id'])
        if device:
            return self.render_json(0, 'ok', {'device_info': device})
        else:
            return self.render_json(-1, '暂时没有数据')


class DeviceDelHandler(BaseHandler):
    """
    设备删除 /device/del
    """
    @requires_auth
    async def post(self, cuser, *args, **kwargs):
        uuid = self.get_argument('uuid', default='')
        if Utils.is_null(uuid):
            return self.render_json(-1, '设备uuid为空')
        user_id = cuser['id']
        device = await self.device_model.get_device_by_uuid_and_userid(
            uuid, user_id)
        if device:
            if await self.device_model.del_device_by_uuid(uuid):
                return self.render_json(0, '删除成功')
            else:
                return self.render_json(-1, '删除失败')
        else:
            return self.render_json(-1, '您要删除的设备不存在')


class DeviceDashboardHandler(BaseHandler):
    """
    设备仪表盘 /device/dashboard
    """
    @requires_auth
    async def get(self, cuser, *args, **kwargs):
        devices = await self.device_model.get_devices_by_userid(cuser['id'])
        if not devices:
            return self.render_json(-1, '暂时没有数据')

        all_count = len(devices)
        online_count = len([i for i in devices if '1' == str(i['offline'])])
        offline_count = len([i for i in devices if '2' == str(i['offline'])])
        active_count = len([i for i in devices if '1' == str(i['status'])])

        data = {
            'all_count': all_count,
            'online_count': online_count,
            'offline_count': offline_count,
            'active_count': active_count,
        }
        return self.render_json(0, 'ok', {'device_dashboard': data})
